package com.limingru.newbee.util;

import java.security.MessageDigest;

public class MD5Util {
    public static String MD5Encode(String password) {
        String resultStr = null;
        String sourceStr = new String(password);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] digest = md5.digest(sourceStr.getBytes("UTF8"));
            resultStr = hexArrayToString(digest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultStr;
    }

    private static String hexArrayToString(byte[] digest) {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < digest.length; ++i) {
            stringBuffer.append(hexToString(digest[i]));
        }

        return stringBuffer.toString();
    }

    private static String hexToString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexString[d1] + hexString[d2];
    }

    public static final String[] hexString = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
    };
}
